package com.baomidou.springboot.config.filter;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.springboot.entity.TbUser;
import com.baomidou.springboot.mapper.TbUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
//    @Autowired
//    TbUserMapper tbUserMapper;
    /**
     * 目标方法执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //        设置跨域
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        return true;
//        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
//        TbUserMapper tbUserMapper = (TbUserMapper)factory.getBean("tbUserMapper");
//        //        暂且不做token校验 纯裸
//        String contextPath = request.getRequestURL().toString();
//        boolean flag = contextPath.contains("/login") || contextPath.contains("/reg") || contextPath.contains("/post/pages");
//
//        if (flag)return true;
//
//
//        String token = String.valueOf(request.getHeader("token"));
//        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getToken, token));
//        if (Objects.isNull(tbUser)) {
////            未登录，返回登陆页
//            response.sendError(500,"您没有权限进行此操作，请先登陆！");
//            response.setStatus(500);
//            return false;
//        } else {
//            //放行
//            return true;
//        }
    }
}